package com.txby.hisJob.config;

import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jta.atomikos.AtomikosDataSourceBean;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.transaction.jta.JtaTransactionManager;

import com.alibaba.druid.pool.xa.DruidXADataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.atomikos.icatch.jta.UserTransactionManager;
import com.atomikos.jdbc.nonxa.AtomikosNonXADataSourceBean;
import com.microsoft.sqlserver.jdbc.SQLServerXADataSource;

@Configuration
public class DruidConfig {
	private Logger logger =Logger.getLogger(DruidConfig.class);
	
    @Value("${spring.datasource.initialSize}")
    private int initialSize;
    @Value("${spring.datasource.minIdle}")
    private int minIdle;
    @Value("${spring.datasource.maxActive}")
    private int maxActive;
    @Value("${spring.datasource.maxWait}")
    private int maxWait;
    @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
    private int timeBetweenEvictionRunsMillis;
    @Value("${spring.datasource.minEvictableIdleTimeMillis}")
    private int minEvictableIdleTimeMillis;
    @Value("${spring.datasource.validationQuery}")
    private String validationQuery;
    @Value("${spring.datasource.testWhileIdle}")
    private boolean testWhileIdle;
    @Value("${spring.datasource.testOnBorrow}")
    private boolean testOnBorrow;
    @Value("${spring.datasource.testOnReturn}")
    private boolean testOnReturn;
    @Value("${spring.datasource.poolPreparedStatements}")
    private boolean poolPreparedStatements;
    @Value("${spring.datasource.filters}")
    private String filters;
    @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
    private int maxPoolPreparedStatementPerConnectionSize;
    
    @Value("{spring.datasource.connectionProperties}")
    private String connectionProperties;
    /**
     * 异构数据源名称
     */
	@Value("${spring.datasource.name}")
	private String txbyDataSourceName;
	@Value("${spring.datasource.driver-class-name}")
	private String driverClassName;
	@Value("${spring.datasource.url}")
	private String dbUrl;
	@Value("${spring.datasource.username}")
	private String username;
	@Value("${spring.datasource.password}")
	private String password;
	 
	@Value("${spring.datasourceHis.name}")
	private String hisDataSourceName;
    @Value("${spring.datasourceHis.driver-class-name}")
    private String driverClassNameHis;
    @Value("${spring.datasourceHis.url}")
    private String dbUrlHis;
    @Value("${spring.datasourceHis.username}")
    private String usernameHis;
    @Value("${spring.datasourceHis.password}")
    private String passwordHis;
    
    
	@Bean
    public ServletRegistrationBean druidServlet() {
        ServletRegistrationBean reg = new ServletRegistrationBean();
        reg.setServlet(new StatViewServlet());
        reg.addUrlMappings("/druid/*");
        reg.addInitParameter("loginUsername", "admin");
        reg.addInitParameter("loginPassword", "123456");
        reg.addInitParameter("allow","192.168.2.74");// IP白名单 (没有配置或者为空，则允许所有访问)
        reg.addInitParameter("deny","192.168.16.111");// IP黑名单 (存在共同时，deny优先于allow)
        reg.addInitParameter("resetEnable","false");// 禁用HTML页面上的“Reset All”功能
        return reg;
    }
	@Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        filterRegistrationBean.addInitParameter("profileEnable", "true");
        filterRegistrationBean.addInitParameter("principalCookieName", "USER_COOKIE");
        filterRegistrationBean.addInitParameter("principalSessionName", "USER_SESSION");
        return filterRegistrationBean;
    }
	
/*    @Bean
    @Primary
    @Qualifier("txbyDataSource")
    public DataSource txbyDataSource(){  
//        DruidDataSource datasource = new DruidDataSource();  
    	  DruidXADataSource datasource = new DruidXADataSource();
        datasource.setUrl(this.dbUrl);  
        datasource.setUsername(username);  
        datasource.setPassword(password);  
        datasource.setDriverClassName(driverClassName);  
        
        datasource.setInitialSize(initialSize);  
        datasource.setMinIdle(minIdle);  
        datasource.setMaxActive(maxActive);  
        datasource.setMaxWait(maxWait);  
        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);  
        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);  
        datasource.setValidationQuery(validationQuery);  
        datasource.setTestWhileIdle(testWhileIdle);  
        datasource.setTestOnBorrow(testOnBorrow);  
        datasource.setTestOnReturn(testOnReturn);  
        datasource.setPoolPreparedStatements(poolPreparedStatements);  
        datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
        try {  
            datasource.setFilters(filters);  
        } catch (SQLException e) {  
            logger.error("druid configuration initialization filter", e);  
        }  
        datasource.setConnectionProperties(connectionProperties);

        AtomikosDataSourceBean atomikosDataSource=new AtomikosDataSourceBean();
        atomikosDataSource.setUniqueResourceName("txbyDataSource");
        atomikosDataSource.setXaDataSource(datasource);
        atomikosDataSource.setMinPoolSize(5);
        atomikosDataSource.setMaxPoolSize(20);
        atomikosDataSource.setTestQuery("SELECT 1");

        return atomikosDataSource;
    }*/
    
/*    @Bean
    @Primary
    @Qualifier("txbyDataSource")
    public DataSource txbyDataSource() {
        AtomikosDataSourceBean atomikosDataSourceBean = new AtomikosDataSourceBean();
        atomikosDataSourceBean.setUniqueResourceName("txbyDataSource");
        atomikosDataSourceBean.setXaDataSourceClassName( "com.mysql.jdbc.jdbc2.optional.MysqlXADataSource");
        Properties properties = new Properties();
        properties.put("URL", this.dbUrl);
        properties.put("user", this.username);
        properties.put("password", this.password);
        atomikosDataSourceBean.setXaProperties(properties);
        return atomikosDataSourceBean;
    }
    @Bean
    @Qualifier("hisDataSource")
    public DataSource hisDataSource() {
    	AtomikosDataSourceBean atomikosDataSourceBean = new AtomikosDataSourceBean();
    	atomikosDataSourceBean.setUniqueResourceName("hisDataSource");
    	atomikosDataSourceBean.setXaDataSourceClassName( "com.microsoft.sqlserver.jdbc.SQLServerXADataSource");
    	Properties properties = new Properties();
    	properties.put("URL", this.dbUrlHis);  
    	properties.put("user", this.usernameHis);
    	properties.put("password", this.passwordHis);
    	atomikosDataSourceBean.setXaProperties(properties);
    	return atomikosDataSourceBean;
    }*/
     
	/**
	 * his数据源
	* @Title: druidDataSourceHis 
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	* @param @return    设定文件 
	* @return DataSource    返回类型 
	* @throws
	 */
   /* @Bean
    @Qualifier("hisDataSource")
    public DataSource hisDataSource(){  
//    	DruidDataSource datasource = new DruidDataSource(); 
    	  DruidXADataSource datasource = new DruidXADataSource();
    	datasource.setUrl(this.dbUrlHis);  
    	datasource.setUsername(usernameHis);  
    	datasource.setPassword(passwordHis);  
    	datasource.setDriverClassName(driverClassNameHis);  
    	
    	datasource.setInitialSize(initialSize);  
    	datasource.setMinIdle(minIdle);  
    	datasource.setMaxActive(maxActive);  
    	datasource.setMaxWait(maxWait);  
    	datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);  
    	datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);  
    	datasource.setValidationQuery(validationQuery);  
    	datasource.setTestWhileIdle(testWhileIdle);  
    	datasource.setTestOnBorrow(testOnBorrow);  
    	datasource.setTestOnReturn(testOnReturn);  
    	datasource.setPoolPreparedStatements(poolPreparedStatements);  
    	 datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
         try {  
             datasource.setFilters(filters);  
         } catch (SQLException e) {  
             logger.error("druid configuration initialization filter", e);  
         }  
         datasource.setConnectionProperties(connectionProperties);
         
         AtomikosDataSourceBean atomikosDataSource=new AtomikosDataSourceBean();
         atomikosDataSource.setUniqueResourceName("hisDataSource");
//         atomikosDataSource.setXaDataSource(datasource);
         atomikosDataSource.setMinPoolSize(5);
         atomikosDataSource.setMaxPoolSize(20);
         atomikosDataSource.setTestQuery("SELECT 1");

         return atomikosDataSource;
    }*/
    @Bean
    @Primary
    @Qualifier("txbyDataSource")
    public DataSource txbyDataSource(){  
//        DruidDataSource datasource = new DruidDataSource();  
    	DruidXADataSource datasource = new DruidXADataSource();
    	datasource.setUrl(this.dbUrl);  
    	datasource.setUsername(username);  
    	datasource.setPassword(password);  
    	datasource.setDriverClassName(driverClassName);  
    	
    	datasource.setInitialSize(initialSize);  
    	datasource.setMinIdle(minIdle);  
    	datasource.setMaxActive(maxActive);  
    	datasource.setMaxWait(maxWait);  
    	datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);  
    	datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);  
    	datasource.setValidationQuery(validationQuery);  
    	datasource.setTestWhileIdle(testWhileIdle);  
    	datasource.setTestOnBorrow(testOnBorrow);  
    	datasource.setTestOnReturn(testOnReturn);  
    	datasource.setPoolPreparedStatements(poolPreparedStatements);  
    	datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
    	try {  
    		datasource.setFilters(filters);  
    	} catch (SQLException e) {  
    		logger.error("druid configuration initialization filter", e);  
    	}  
    	datasource.setConnectionProperties(connectionProperties);
    	
    	AtomikosDataSourceBean atomikosDataSource=new AtomikosDataSourceBean();
    	atomikosDataSource.setUniqueResourceName("txbyDataSource");
    	atomikosDataSource.setXaDataSource(datasource);
    	atomikosDataSource.setMinPoolSize(5);
    	atomikosDataSource.setMaxPoolSize(20);
    	atomikosDataSource.setTestQuery("SELECT 1");
    	
    	return atomikosDataSource;
    }
    
    
    /**
     * his数据源
     * @Title: druidDataSourceHis 
     * @Description: TODO(这里用一句话描述这个方法的作用) 
     * @param @return    设定文件 
     * @return DataSource    返回类型 
     * @throws
     */
    @Bean
    @Qualifier("hisDataSource")
    public DataSource hisDataSource(){  
//    	DruidDataSource datasource = new DruidDataSource(); 
    	DruidXADataSource datasource = new DruidXADataSource();
    	datasource.setUrl(this.dbUrlHis);  
    	datasource.setUsername(usernameHis);  
    	datasource.setPassword(passwordHis);  
    	datasource.setDriverClassName(driverClassNameHis);  
    	
    	datasource.setInitialSize(initialSize);  
    	datasource.setMinIdle(minIdle);  
    	datasource.setMaxActive(maxActive);  
    	datasource.setMaxWait(maxWait);  
    	datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);  
    	datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);  
    	datasource.setValidationQuery(validationQuery);  
    	datasource.setTestWhileIdle(testWhileIdle);  
    	datasource.setTestOnBorrow(testOnBorrow);  
    	datasource.setTestOnReturn(testOnReturn);  
    	datasource.setPoolPreparedStatements(poolPreparedStatements);  
    	datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
    	try {  
    		datasource.setFilters(filters);  
    	} catch (SQLException e) {  
    		logger.error("druid configuration initialization filter", e);  
    	}  
    	datasource.setConnectionProperties(connectionProperties);
    	
    	AtomikosDataSourceBean atomikosDataSource=new AtomikosDataSourceBean();
    	atomikosDataSource.setUniqueResourceName("hisDataSource");
         atomikosDataSource.setXaDataSource(datasource);
    	atomikosDataSource.setMinPoolSize(5);
    	atomikosDataSource.setMaxPoolSize(20);
    	atomikosDataSource.setTestQuery("SELECT 1");
    	
    	return datasource;
    }
   /* 
    @Bean(destroyMethod = "close", initMethod = "init")
    public UserTransactionManager userTransactionManager() {
        UserTransactionManager userTransactionManager = new UserTransactionManager();
        userTransactionManager.setForceShutdown(false);
        return userTransactionManager;
    }*/

    /**
     * jta transactionManager
     *
     * @return
     */
   /* @Bean
    public JtaTransactionManager transactionManager() {
        JtaTransactionManager jtaTransactionManager = new JtaTransactionManager();
        jtaTransactionManager.setTransactionManager(userTransactionManager());
        return jtaTransactionManager;
    }*/
    
}